package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-03-27
 * Time: 11:06
 */

@WebServlet("/myBlog")
public class MyBlogServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 前端发来请求获取数据库中的指定文章 ContentType:application/json; charset = utf8;

        resp.setContentType("application/json; charset = utf8");
        ObjectMapper objectMapper = new ObjectMapper();
        // 获取当前会话
        HttpSession session = req.getSession(false);
        if(session == null) {
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(404);
            return;
        }
        // 获取 userId
        // 查询 userId 对应文章
        BlogDao blogDao = new BlogDao();
        List<Blog> blogs = blogDao.selectBlogByUserId(user.getUserId());
        String respJson = objectMapper.writeValueAsString(blogs);
        resp.getWriter().write(respJson);

    }
}
